package main

import (
	"fmt"
	"sync"
	"time"
)

var (
	locker2 *sync.Mutex
	cond2   *sync.Cond
)

func Broadcastest(x int) {
	//2.1.获取锁
	cond2.L.Lock() //
	//2.2.等待通知  暂时阻塞
	cond2.Wait()
	fmt.Println(x)
	time.Sleep(time.Second * 1)
	cond2.L.Unlock() // 释放锁，不释放锁,其它被唤醒的gouroutine将没法继续执行
}

func main() {
	//示例-:演示cond.signal
	fmt.Println("---------------example:Use of Cond.Signal---------------")
	locker := new(sync.Mutex)
	cond := sync.NewCond(locker)
	done := false

	cond.L.Lock()

	go func() {
		done = true
		fmt.Printf("goroutine in cond.signal\n")
		cond.Signal()
	}()

	//if !done {
	for !done { //在循环中等待条件的满足比较合适
		fmt.Printf("in cond wait\n")
		cond.Wait()
	}

	cond.L.Unlock()
	fmt.Println("now done is ", done)
	//示例二:演示cond.broadcast
	fmt.Println("---------------example:Use of Cond.Broadcast---------------")

	locker2 = new(sync.Mutex)
	cond2 = sync.NewCond(locker2)
	for i := 0; i < 10; i++ {
		go Broadcastest(i)
	}
	fmt.Println("start all")
	//2.3.下发广播给所有等待的goroutine
	cond2.Broadcast()
	time.Sleep(time.Second * 10)
}
